<template>
  <div>
    <a-card title="工单信息录入">
      <SchemaForm>
      </SchemaForm>
      <div style="text-align: center;">
        <Space>
          <AButton color="rgb(64,169,255)" @click="handleSubmitWorkOrder"> 生成工单 </AButton>
          <AButton color="rgb(0,225,0)" @click="sendsModal"> 派单</AButton>
          <AButton color="rgb(0,225,0)" @click="openMoreSendsModal"> 多单位派单</AButton>
          <AButton color="rgb(0,225,0)" @click="openReplyModal"> 结单</AButton>
          <AButton color="rgb(64,169,255)" @click="completeWorkOrder"> 完成工单 </AButton>
          <AButton color="rgb(82,196,26)" @click="incomingCalls"> 来电记录 </AButton>
          <AButton color="rgb(82,196,26)" @click="addressQuery"> 地址联查 </AButton>
          <AButton color="rgb(82,196,26)" @click="markerMapHandle"> 图上标点 </AButton>
          <!-- <AButton color="rgb(245,245,245)" style="color:black" @click="handleReset"> 重置 </AButton> -->
          <AButton color="rgb(245,245,245)" style="color:black" @click="handleClose"> 关闭 </AButton>
          <AButton color="rgb(64,169,255)" v-if="hasBack" @click="goBack">
            返回
          </AButton>
        </Space>
      </div>
    </a-card>
    <!-- 来电记录查询模块 -->
    <DraggableModal destroyOnClose="true" v-model:visible="incomingCallsVisible" title="来电记录" :centered=false
      width="auto;" :body-style="{ height: '50vh', width: '100%' }" :keyboard="false" :fullscreen=false :closable=true
      footer="">
      <div>
        <DynamicTable row-key="id" :scroll="{ x: 600 }" show-index :showToolBar="false" :data-request="listCallsColumns"
          :columns="incomingCallsColumns" bordered size="small">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'workOrderNumber'">
              <a class="workOrderNumber" v-on:click="openMenuModal(record)">{{ record.workOrderNumber }} </a>
            </template>
          </template>
        </DynamicTable>
      </div>
    </DraggableModal>
    <!-- 地址联查模块 -->
    <DraggableModal destroyOnClose="true" v-model:visible="addressQueryVisible" title="地址联查" :centered=false width="auto;"
      :body-style="{ height: '50vh', width: '100%' }" :keyboard="false" :fullscreen=false :closable=true footer="">
      <div>
        <DynamicTable row-key="id" :scroll="{ x: 1000 }" header-title="" :showToolBar="false" show-index
          :data-request="listaddressQuery" :columns="addressQueryColumns" bordered size="small">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'workOrderNumber'">
              <a class="workOrderNumber" v-on:click="openMenuModal(record)">{{ record.workOrderNumber }} </a>
            </template>
          </template>
        </DynamicTable>
      </div>
    </DraggableModal>
    <!-- 图上标点模块 -->
    <DraggableModal destroyOnClose="true" v-model:visible="markerMapVisible" :centered=false width="auto;"
      :body-style="{ height: '510px', padding: '5px' }" :keyboard="false" title="图上标点" :fullscreen=false :closable=true
      footer="">
      <marker-map :longitude="longitude" :latitude="latitude" :address="address" @bindEvent="updateCoordinate"></marker-map>
    </DraggableModal>

  </div>
</template>

<script lang="ts" setup>
import { workorderschemas, moresendsschemas, uploadFileObject } from './formSchemas';
import { Space } from 'ant-design-vue';
import { useForm } from '@/components/core/schema-form';
import { getInitWorkOrder, createWorkOrder, updateWorkOrder, dispatchWorkOrder, listWorkOrder, getWorkOrder } from '@/api/workorder/order';
import { DraggableModal } from '@/components/core/draggable-modal';
import { AButton } from '@/components/basic/button';
import { reactive, ref, onMounted } from 'vue';
import { useFormModal } from '@/hooks/useModal/useFormModal';
import { addReply, getInitReply } from '@/api/workorder/reply';
import { workOrderReplyschemas, uploadFileReplyObject } from '@/views/workorder/reply/formSchemas';
import { uploadAttament } from '../common/common';
import { incomingCallsColumns, addressQueryColumns, pageDataObj } from './columns'
import { LoadDataParams, useTable } from '@/components/core/dynamic-table';
import { getCategaryList } from '@/api/workorder/categary';
import { formatCategary2Tree } from '@/core/permission/utils';
import dayjs from 'dayjs';
import markerMap from '@/views/workorder/map/index.vue'
import { listAttament } from '@/api/workorder/common/attachment';

defineOptions({
  name: 'AddWorkOrder',
});
// 工单信息
let workOrderObj = reactive([]);
const incomingCallsVisible = ref(false);
const addressQueryVisible = ref(false);
const markerMapVisible = ref(false);
const hasBack = ref(false);
// 经纬度信息
let longitude = ref(String);
let latitude = ref(String);
let address = ref('');



onMounted(async () => {
  if (history.state.record) {
    let cxjsw = JSON.parse(history.state.record);
    workOrderObj.problemDesc = cxjsw?.wtms; // 问题描述
    workOrderObj.processingPeriod = Number(cxjsw?.clqx); // 处理期限
    cxjsw?.linkPhone ? workOrderObj.contactsInfo = cxjsw?.linkPhone : ""; // 联系方式
    cxjsw?.linkperson ? workOrderObj.contacts = cxjsw?.linkperson : ""; // 联系人
    cxjsw?.xxlyId ? workOrderObj.infoSerrces = String(cxjsw?.xxlyId) : ""; // 信息来源
    cxjsw?.lat ? workOrderObj.latitude = String(cxjsw?.lat) : ""; // 经度
    cxjsw?.lon ? workOrderObj.longitude = String(cxjsw?.lon) : ""; // 维度
    workOrderObj.returnVisit = '2'; // 手否回访
    workOrderObj.remarks = cxjsw?.beizhu; // 中心回复
    workOrderObj.extOrderNumber = cxjsw?.guid; // 外部单号
    dynamicFormRef?.setFieldsValue({
      ...workOrderObj
    });
    hasBack.value = true;
  }
  if (history.state.workOrder) {
    workOrderObj = JSON.parse(history.state.workOrder);
    dynamicFormRef?.setFieldsValue({
      ...workOrderObj
    });
    hasBack.value = true;
    // 添加主工单附件
    let data = await listAttament({ 'bussId': workOrderObj.id });
    let initFileData: any[] = [];
    data.forEach((fileData) => {
      initFileData.push({
        uid: fileData.id,
        name: fileData.fileName,
        status: 'done',
      });
    })
    dynamicFormRef?.updateSchema({
      field: 'attament',
      componentProps: {
        fileList: initFileData
      },
    })
  }
})

// 打开回复页面
const [showModal] = useFormModal();

// 初始化表单内容
const [SchemaForm, dynamicFormRef] = useForm({
  labelWidth: 100,
  schemas: workorderschemas,
  showSubmitButton: false,
  showResetButton: false,
});



// 表格数据
const [DynamicTable, dynamicTableInstance] = useTable({
  formProps: {
    fieldMapToTime: [
      ['acceptTime', ['acceptStartTime', 'acceptEndTime'], 'YYYY-MM-DD HH:mm:ss'],
    ],
    autoAdvancedLine: 1,
  }
});

/**
 * @description 修改工单坐标信息
 * @param lng
 * @param lat
 */
const updateCoordinate = async (lng, lat, address) => {
  longitude = lng;
  latitude = lat;
  dynamicFormRef?.setFieldsValue({
    longitude: lng, // 经度
    latitude: lat, // 维度
    occAddress: address // 发生地址
  });
}

// 初始化表单数据信息
if (!history.state.workOrder) {
  initData();
}
async function initData() {
  const data = await getInitWorkOrder();
  dynamicFormRef?.setFieldsValue({
    workOrderNumber: data.workOrderNumber,
    acceptNumber: data.acceptNumber,
    acceptTime: data.acceptTime,
  });
}
/**
 * @description  生成工单
 */
async function handleSubmitWorkOrder() {
  let formData = {
    ...dynamicFormRef?.getFieldsValue(),
  }
  // 判断单据状态  只有新工单状态的单据才可以修改    // 保存内容
  formData.workOrderStatus == '0' ? await handleSave(formData) : '';
}

/**
 * @description 完成工单
 */
async function completeWorkOrder() {
  let formData = {
    ...dynamicFormRef?.getFieldsValue(),
    workOrderStatus: 5 // 工单状态标记为完成
  }
  await handleSave(formData); // 保存内容
  // 禁用表单数据
  disableForm();
}


/**
 * @deprecated 打开来电记录
 */
async function incomingCalls() {
  getCategaryList({ "sysCode": 'workorder', 'visible': '0', 'categaryCode': 'industry_type' }).then((res) => {
    pageDataObj.industryTypeDict = res.map((item) => ({
      label: item.name,
      value: item.code,
    }));
    dynamicTableInstance?.getQueryFormRef()?.updateSchema([{
      field: `industryType`,
      componentProps: {
        treeData: formatCategary2Tree(res, '0'),
      },
    }]);
    dynamicTableInstance?.getQueryFormRef()?.setFieldsValue({
      callerNumber: dynamicFormRef?.getFieldsValue().callerNumber
    })
  })
  // 获取到当前工单来单手机号 并做查询 （三个月内的数据）
  incomingCallsVisible.value = true;
}

/**
 * @description 打开地图描点
 */

async function markerMapHandle() {
  address  = dynamicFormRef?.getFieldsValue().occAddress;
  markerMapVisible.value = true;
}

/**
 *
 * @deprecated 来电查数据
 */
const listCallsColumns = async (params: LoadDataParams) => {
  if (dynamicFormRef?.getFieldsValue().callerNumber) {
    params.callerNumber = dynamicFormRef?.getFieldsValue().callerNumber
  }
  // 半年内的数据
  if (!params.acceptStartTime) {
    params.acceptStartTime = dayjs(new Date()).subtract(6, 'month').format("YYYY-MM-DD HH:mm:ss")
  }
  return await listWorkOrder(params);
};

const goBack = async () => {
  history.go(-1)
}

/**
 *
 * @deprecated 地址联查
 */
const listaddressQuery = async (params: LoadDataParams) => {
  if (dynamicFormRef?.getFieldsValue().occAddress) {
    params.occAddress = dynamicFormRef?.getFieldsValue().occAddress
  }
  // 半年内的数据
  if (!params.acceptStartTime) {
    params.acceptStartTime = dayjs(new Date()).subtract(7, 'day').format("YYYY-MM-DD HH:mm:ss")
  }
  return await listWorkOrder(params);
};

/**
 * @deprecated 打开地址联查
 */
async function addressQuery() {
  addressQueryVisible.value = true;
  getCategaryList({ "sysCode": 'workorder',  'visible': '0', 'categaryCode': 'industry_type' }).then((res) => {
    pageDataObj.industryTypeDict = res.map((item) => ({
      label: item.name,
      value: item.code,
    }));
    dynamicTableInstance?.getQueryFormRef()?.updateSchema({
      field: `industryType`,
      componentProps: {
        treeData: formatCategary2Tree(res, '0'),
      },
    });
    dynamicTableInstance?.getQueryFormRef()?.setFieldsValue({
      occAddress: dynamicFormRef?.getFieldsValue().occAddress
    })
  });
}

/**
 * @description 打开新增回复单填报页面
 */
const openReplyModal = async () => {
  const [replyFormRef] = await showModal({
    modalProps: {
      title: `添加回复信息`,
      width: '40%',
      cancelText: '关闭',
      onFinish: async (values) => {
        // 保存工单信息
        await handleSubmitWorkOrder()
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        // 保存回复单信息
        let reply = await addReply(values);
        // 上传附件并保存附件信息
        // 附件上传(回复单)
        await uploadAttament(uploadFileReplyObject.uploadFileList, 'reply', reply.id,);
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: workOrderReplyschemas,
    },
  });
  // 初始化回复单基本信息
  const data = await getInitReply();
  replyFormRef?.setFieldsValue({
    replyNo: data.replyNo,
    replyerId: data.sysOrg.id,
    replyer: data.sysOrg.name,
  });
};



/**
 * @deprecated 派单选择页面
 */
const sendsModal = async () => {
  // 保存工单信息
  await handleSubmitWorkOrder()
  // 多单位派单
  await dispatchWorkOrder({ workOrderNumber: dynamicFormRef?.getFieldsValue().workOrderNumber });
  // 派单成功后将单据状态改为派单
  workOrderObj = await getWorkOrder(workOrderObj.id)
  dynamicFormRef?.setFieldsValue({
    ...workOrderObj
  });
  // 禁用表单数据
  // disableForm();
  setTimeout(() => { window.location.reload() }, 1500);
};

/**
 * @deprecated 多单位派单选择页面
 */
const openMoreSendsModal = async () => {
  const [moreSendsFormRef] = await showModal({
    modalProps: {
      title: `多单位派单`,
      width: '40%',
      cancelText: '关闭',
      onFinish: async (values) => {
        // 保存工单信息
        await handleSubmitWorkOrder()
        // 赋值工单编号（感觉id比较合适 ~~~）
        values.workOrderNumber = dynamicFormRef?.getFieldsValue().workOrderNumber;
        // 多单位派单
        await dispatchWorkOrder(values);
        // 派单成功后将单据状态改为派单
        await dynamicFormRef?.setFieldsValue({ workOrderStatus: '1' })
        // 禁用表单数据
        // disableForm();
        setTimeout(() => { window.location.reload() }, 1500);

      },
    },
    formProps: {
      labelWidth: 100,
      schemas: moresendsschemas,
      initialValues: ({
        mainDept: dynamicFormRef?.getFieldsValue().responsibleUnit
      })
    },
  });
};

/**
 * @description 生成(保存工单)
 */
async function handleSave(formDataParams: any) {
  const result = await dynamicFormRef?.validateFields();
  if (result) {
    workOrderObj = await (formDataParams.id ? updateWorkOrder : createWorkOrder)(formDataParams);
    // 保存工单信息后数据返填回去
    await dynamicFormRef?.setFieldsValue({
      ...workOrderObj
    });
    // 附件上传（工单信息）新增工单数据  先保存工单数据再上传数据；修改工单数据：直接删除附件或者上传附件 此处不处理
    if (!formDataParams.id) {
      await uploadAttament(uploadFileObject.uploadFileList, 'workorder', workOrderObj.id);
    }
  }
}

/**
 * @description 将内容重置
 */
// async function handleReset() {
//   dynamicFormRef?.updateSchema({
//     field: 'attament',
//     componentProps: {
//       fileList: []
//     }
//   });
//   dynamicFormRef?.resetFields();
//   initData();
//   // 无效禁用
//   dynamicFormRef?.setSchemaFormProps({
//     disabled: false,
//     requiredMark: true,
//   });
// }

// 关闭tab页签
function handleClose(){
  top?.postMessage('xinxidengji', '*');
}

// 禁用表单
function disableForm() {
  dynamicFormRef?.setSchemaFormProps({
    disabled: true,
    requiredMark: false,
  });
}

/**
 * @description 打开新增/编辑弹窗
 */
const openMenuModal = async (record: Partial) => {
  const [formRef] = await showModal({
    modalProps: {
      title: `${record.id ? '查看' : '新增'}工单信息`,
      width: '80%',
      bodyStyle: { height: '60vh' },
      okButtonProps: { disabled: true },
      cancelText: '关闭',
      onFinish: async (values) => {
        record.id && (values.workOrderId = record.id);
        await (record.id ? updateWorkOrder : createWorkOrder)(values);
        dynamicTableInstance?.reload();
      },
    },
    formProps: {
      labelWidth: 100,
      schemas: workorderschemas,
    },
  });
  // 填充表单数据
  formRef?.setFieldsValue({
    ...record,
  });
  // 设置表单禁用属性
  formRef?.setSchemaFormProps({
    disabled: true,
    requiredMark: false,
  });
  // 非必填信息清除
  formRef?.updateSchema({
    field: 'remarks',
    componentProps: {
      placeholder: "",
    },
  })
  // 添加附件列表
  let data = await listAttament({ 'bussId': record.id });
  let initFileData = [];
  data.forEach((fileData) => {
    initFileData.push({
      uid: fileData.id,
      name: fileData.fileName,
      status: 'done',
    });
  })
  formRef?.updateSchema({
    field: 'attament',
    componentProps: {
      fileList: initFileData
    },
  })
};



</script>
<style lang="less">
.ant-input-number {
  width: 100%;
}

.workOrderNumber {
  color: #1890ff;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.ant-tooltip-inner{
  width: 500px;
}
</style>
